package com.boarsoft.boar.file.biz;

import java.util.List;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.entity.AppFile;
import com.boarsoft.boar.entity.AppInfo;
import com.boarsoft.boar.entity.FileInfo;
import com.boarsoft.boar.file.FileAppBiz;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component
public class FileAppBizImpl extends SimpleBizImpl implements FileAppBiz {
	/**
	 * 根据fileId查询返回fileId【已关联的】所有AppInfo的集合 表app_inf和表app_file的关联查询
	 */
	@Override
	@Transactional(readOnly = true)
	public PagedResult<AppInfo> list(String fileId, boolean in, String key, String orderBy, int pageNo, int pageSize) {
		StringBuilder sb = new StringBuilder();
		sb.append(" from ").append(AppInfo.class.getName())//
				.append(" a where a.id ").append(in ? "in" : "not in")//
				.append(" (select af.appId from ").append(AppFile.class.getName())//
				.append(" af where af.fileId='").append(fileId).append("')");
		if (Util.strIsNotEmpty(key)) {
			sb.append(" and (a.code like '%").append(key);
			sb.append("%' or a.name like '%").append(key);
			sb.append("%' or a.memo like '%").append(key);
			sb.append("%')");
		}
		int total = dao.getTotal("select count(a.id)".concat(sb.toString()));
		if (Util.strIsNotEmpty(orderBy)) {
			String ob = Util.array2str(("a.".concat(orderBy))//
					.replaceAll(",", ",").split(","), ",");
			sb.append(" order by ").append(ob);
		} else {
			sb.append(" order by a.name");
		}
		List<AppInfo> lt = dao.list(//
				"select a".concat(sb.toString()), AppInfo.class, pageNo, pageSize);
		return new PagedResult<AppInfo>(total, lt, pageNo, pageSize);
	}

	@Override
	@Transactional(readOnly = true)
	public List<AppInfo> list(String fileId) {
		StringBuilder sb = new StringBuilder().append("select a from ")//
				.append(FileInfo.class.getName()).append(" c join c.apps a")//
				.append(" where c.id='").append(fileId).append("'");
		return dao.list(sb.toString(), AppInfo.class);
	}
}